<template>
    <div class="chart-panel clearfix" style="position: relative">
        <compSearch
            ref="search"
            :data="searchData"
            align="left"
            @on-search="handleSearch"
        ></compSearch>
        <div class="date-container">
            <div class="padding-top-15" style="display: flex">
                <div>
                    <RadioGroup
                        class="margin-bottom-10"
                        size="default"
                        v-model="queryDate"
                        type="button"
                        button-style="solid"
                        @on-change="handleCustomDateAndSearch"
                    >
                        <Radio v-for="item in dateQuery" :key="item.value" :label="item.value">{{item.label}}</Radio>
                    </RadioGroup>
                    <Poptip
                        v-if="datePickerOption.show"
                        trigger="hover"
                        :content="$t(datePickerOption.langKey, { defaultValue: '时间选择' })"
                        word-wrap
                        ><Icon class="title-question-icon" type="md-help-circle"
                    /></Poptip>
                </div>
                <div class="margin-left-20">
                    <Form>
                        <FormItem :labelWidth="80" label="自定义日期">
                            <DatePicker
                                v-model="customDate"
                                type="daterange"
                                :clearable="false"
                                @on-change="handleSearch($refs.search.formData)"
                            ></DatePicker>
                        </FormItem>
                    </Form>
                </div>
            </div>
        </div>
        <div class="card-container">
            <compCard
                class="card-main"
                v-for="key in Object.keys(cardData)"
                :key="key"
                v-bind="cardData[key]"
            ></compCard>
        </div>
        <div class="chart-panel-container">
            <compHandleChart
                v-for="item in chartList"
                :key="item.key"
                v-bind="item"
            ></compHandleChart>
        </div>
        <Spin v-if="loading" fix></Spin>
    </div>
</template>

<script>
import moment from "moment";
import compSearch from "@components/templates/searchs.vue";
import compCard from "@components/templates/card.vue";
import compHandleChart from "@components/templates/chart/handlechart.vue";
export default {
    components: {
        compSearch,
        compCard,
        compHandleChart,
    },
    data() {
        return {
            loading: false,
            productList: [],
            accountList: [],
            customDate: [],
            chartList: [],
        };
    },
    async created() {
        await this.init();
    },
    methods: {
        handleCustomDate(queryDate) {
            let startDate = moment().subtract(queryDate, "days").toDate();
            let endDate = moment().toDate();
            this.customDate = [startDate, endDate];
        },
        async handleCustomDateAndSearch(queryDate) {
            this.handleCustomDate(queryDate);
            let data = {};
            await this.$nextTick(() => {
                data = this.$refs.search.formData;
            });
            this.handleSearch(data);
        },
        async init() {
            this.handleCustomDate(this.queryDate);
        },
        // 搜索
        async handleSearch(data) {
            let isReset = !data;
            if (isReset) {
                this.queryDate = 7;
                this.handleCustomDate(this.queryDate);
            }
            let format = "YYYY-MM-DD 00:00:00";
            let startDate = moment(this.customDate[0]);
            let endDate = moment(this.customDate[1]);
            let tongbiStartDate = moment(startDate).subtract(this.year, "days");
            let tongbiEndDate = moment(endDate).subtract(this.year, "days");

            let daysDuration = endDate.diff(startDate, "days");
            let testArr = [this.week, this.mouth, this.mouth * 3, this.year];
            let queryDate = 0;
            for (let i = 0; i < testArr.length; ) {
                queryDate = this.handleQueryDate(
                    startDate,
                    endDate,
                    testArr[i]
                );
                if (queryDate == 0) {
                    i++;
                } else {
                    break;
                }
            }
            
            this.queryDate = queryDate;

            let nowArgs = this.handleRequestData(
                data,
                startDate,
                endDate,
                format
            );
            this.loading = true;
            let nowDatePromise = new Promise((resolve, reject) => {
                this.ajaxRequest({
                    component_id: 2,
                    args: JSON.stringify(nowArgs),
                }).then(resolve, reject);
            }).catch((e) => {
                console.log(e)
            });

            let oldArgs = this.handleRequestData(
                data,
                tongbiStartDate,
                tongbiEndDate,
                format
            );
            let oldDatePromise = new Promise((resolve, reject) => {
                this.ajaxRequest({
                    component_id: 2,
                    args: JSON.stringify(oldArgs),
                }).then(resolve, reject);
            }).catch((e) => {
                console.log(e)
            });
            this.chartList = this.defaultChartData.map((item) => {
                return {
                    ajaxRequest: this.ajaxRequest,
                    ...item,
                    requestData: {
                        ...nowArgs,
                        component_id: item.id,
                    },
                };
            });
            // // 图表数据-新增客诉数量趋势图
            // let chartPromise1 = new Promise((resolve, reject) => {
            //     this.ajaxRequest({
            //         component_id: 3,
            //         args: JSON.stringify(nowArgs),
            //     }).then(resolve, reject);
            // });
            await Promise.all([
                nowDatePromise,
                oldDatePromise,
                // chartPromise1,
            ]).then(
                (dataList) => {
                    // console.log("dataList", dataList);
                    Object.keys(this.cardData).map((key) => {
                        this.handleCardData(key, dataList);
                    });
                    // console.log("cardData", this.cardData);
                    // // 新增客诉数量趋势图
                    // this.handleChart1(dataList[2]);
                },
                (err) => {
                    this.$Message.error(err.message);
                    this.loading = false;
                }
            );
            this.loading = false;
        },
        handleCardData(key, dataList) {
            if (this.customCardData) {
                return this.customCardData();
            }
            let newData = dataList[0].data.data[0][key];
            let oldData = dataList[1].data.data[0][key];
            // 同比
            let tongbi = ((newData - oldData) / oldData) * 100;
            tongbi = tongbi.toFixed(1);
            // 环比
            let huanbi = -1;
            if (newData - oldData == 0) {
                tongbi = 0;
            } else if (newData == 0) {
                tongbi = -100;
            } else if (oldData == 0) {
                tongbi = 100;
            }
            this.cardData[key] = {
                ...this.cardData[key],
                title: this.cardData[key].title,
                count: newData,
                percentList: [
                    {
                        label: "同比",
                        value: tongbi,
                    },
                    // {
                    //     label: "环比",
                    //     value: huanbi,
                    // },
                ],
            };
        },
        handleQueryDate(startDate, endDate, duration) {
            let nowDate = moment();
            let copyStartDate = moment(startDate);
            let copyEndDate = moment(endDate);
            let dateDuration = copyEndDate.diff(copyStartDate, "days");
            let isReturn = false;
            // 开始日期与结束日期正好相隔duration天
            if (dateDuration == duration) {
                // 结束日期是否与当前是同一天
                if (copyEndDate.diff(nowDate, "days") < 1) {
                    isReturn = true;
                    // if (copyEndDate.subtract(duration, "days") == copyStartDate) {
                    //     isReturn = true;
                    // }
                }
            }
            if (isReturn) {
                return duration;
            } else {
                return 0;
            }
        },
        handleRequestData(
            data,
            startDate,
            endDate,
            format = "YYYY-MM-DD HH:mm:ss"
        ) {
            let args = {
                org_id: global.SYSID,
                line_id: (data && data.lineId) || "",
                account_flag: (data && data.accountFlag) || "",
                seller_sku: (data && data.sellerSku) || "",
                start_at: startDate ? startDate.format(format) : "",
                end_at: endDate.format(format) || "",
                issue_status: "",
                issue_category_status: "",
            };
            return args;
        },
        handleChart1(data) {
            console.log("chartData", data);
        },
    },
};
</script>

<style lang="scss" scoped>
.chart-panel {
    background-color: #f6f8f9;
}
.ivu-radio-wrapper-checked {
    background-color: #2d8cf0;
    color: #fff;

    &:hover {
        background-color: #57a3f3;
        color: #fff;
    }
}
.title-question-icon {
    font-size: 12px;
    color: #66b1ff;
    margin-left: 5px;
    position: relative;
    top: -3px;
    cursor: pointer;
}
.date-container {
    // background-color: #fff;
    padding: 0 15px;
}
// .card-container,
// .chart-panel-container {
//     // background-color: #fff;
//     // padding: 15px;
// }
.card-container {
    display: flex;
    justify-content: space-around;
    margin: 0 20px;
    .card-main {
        margin-right: 15px;
        &:last-child {
            margin-right: 0;
        }
    }
}
.chart-panel-container {
    padding: 15px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    border: 1px solid #e4e7ed;
    background-color: #fff;
    margin: 0 20px;
    margin-top: 15px;
    // border: 1px solid #e4e7ed;
}
</style>